<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/9/17
 * Time: 下午12:46
 */

namespace App\Library\Mall\Shop;


use App\Library\AuthenticatedUser;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

trait ShopManagers
{
    use AuthenticatedUser;
    /**
     * @param Request $request
     * @return \App\Models\Shop|bool|\Illuminate\Database\Eloquent\Model|mixed
     */
    public function store(Request $request)
    {

        $newshop = Arr::only($request->post('shop', []), [
            'shop_name',
            'logo',
            'type',
            'phone',
            'province',
            'city',
            'district',
            'street',
            'description',
            'lat',
            'lng'
        ]);
        $newcontent = Arr::only($request->post('content',[]), ['content']);
        if ($newshop['shop_name'] && $newshop['phone']) {
            if ($shop = $this->user()->shop) {
                $shop->update($newshop);
            }else {
                $shop = $this->user()->shop()->create($newshop);
            }
            if (isset($newcontent['content'])){
                if ($newshop) $shop->content()->update($newcontent);
            }
            return $this->sendShopSavedResponse($request, $shop);
        }

        return $this->sendShopSavedFailedResponse($request);
    }

    /**
     * @param Request $request
     * @param $shop
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendShopSavedResponse(Request $request, $shop)
    {
        return ajaxReturn(['shop'=>$shop]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendShopSavedFailedResponse(Request $request)
    {
        return ajaxError(201, 'invalid parameter');
    }
}
